package com.example.controller;

import com.example.entity.BaseResponse;
import com.example.entity.MaterialEntity;
import com.example.entity.MaterialSearchEntity;
import com.example.entity.ResultBody;
import com.example.service.MaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class MaterialController {
    @Autowired
    MaterialService materialService;

    @RequestMapping("/getMaterial")
    public MaterialEntity getTask(int id) {
        return new MaterialEntity();
    }

    /**
     * 列出所有设备信息
     *
     * @return 设备信息列表的封装对象
     */
    @RequestMapping("/listMaterial")
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public BaseResponse<MaterialEntity> listTask() {
        List<MaterialEntity> materialList = materialService.findAll();
        return new BaseResponse<MaterialEntity>(0, "success",
                materialList.size(), materialList);
    }
    /**
     * 保存设备信息
     *
     * @param method 设备保存方法，可选值为"添加"或"修改"
     * @param materialEntity 设备信息实体类
     * @return 返回操作结果的封装对象
     */
    @RequestMapping("/saveMaterial")
    @ResponseBody
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public ResultBody saveMaterial(String method,MaterialEntity materialEntity){
        System.out.println(materialEntity.toString());
        System.out.println(method);
        if (materialService.saveMaterial(method,materialEntity)){
            return new ResultBody(0, "success");
        } else{
            return new ResultBody(1, "fail");
        }
    }
    /**
     * 删除设备信息
     *
     * @param id 设备ID
     * @return 返回操作结果的封装对象
     */
    @RequestMapping("/deleteMaterial")
    @ResponseBody
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public ResultBody deleteMaterial(int id){
        if (materialService.deleteMaterial(id)){
            return new ResultBody(0, "success");
        } else{
            return new ResultBody(1, "fail");
        }
    }

    /**
     * 查询设备信息
     *
     * @param materialSearch 查询条件实体类
     * @return 设备信息列表的封装对象
     */
    @RequestMapping("/materialSearch")
    @ResponseBody
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public BaseResponse<MaterialEntity> materialSearch(MaterialSearchEntity materialSearch) {
        System.out.println(materialSearch);
        materialSearch.setStart((materialSearch.getPage()-1)*materialSearch.getLimit());
        List<MaterialEntity> materialList = materialService.materialSearch(materialSearch);
        return new BaseResponse<MaterialEntity>(0, "success",
                materialService.materialSearchCount(materialSearch), materialList);
    }

}
